const Order = require('../entity/Order')
const {Op} = require('sequelize');

async function saveOrder(req) {
    const {id, orderContext, price, createTime, status, phone,} = req.body;
    const existingMan = await Order.findOne({where: {id: id}});
    if (existingMan) {
        // 如果存在，则执行更新操作
        const updatedOrder = await Order.update({
            orderContext: orderContext,
            price: price,
            createTime: createTime,
            status: status,
            phone: phone
        }, {
            where: {id: id}
        });
        return updatedOrder;
    } else {
        // 如果不存在，则执行插入操作
        const newOrder = await Order.create({
            orderContext: orderContext,
            price: price,
            createTime: createTime,
            status: status,
            phone: phone
        });
        return newOrder;
    }
}

async function findPage(req) {
    const {pageNum, pageSize, dateRange, searchPhone, searchId} = req.query;
    const pageNumInt = parseInt(pageNum);
    const pageSizeInt = parseInt(pageSize);
    const offset = (pageNumInt - 1) * pageSizeInt; // 计算偏移量

    // 查询数据库获取总记录数
    let queryOptions = {
        offset,
        limit: pageSizeInt, // 使用 limit 控制返回的行数
    };
    queryOptions.where = {};
    if (searchPhone) {
        queryOptions.where.phone = {
            [Op.like]: `%${searchPhone}%`
        };
    }
    if (searchId) {
        queryOptions.where.id = {
            [Op.like]: `%${searchId}%`
        };
    }
    if (dateRange) {
        const start = new Date(dateRange[0])
        const end = new Date(dateRange[1])
        start.setMinutes(start.getMinutes() - start.getTimezoneOffset());
        end.setMinutes(end.getMinutes() - end.getTimezoneOffset());
        queryOptions.where.createTime = {
            [Op.between]: [start, end]
        };
    }
    // 查询数据库获取总记录数
    const totalCount = await Order.count(queryOptions);
    queryOptions.attributes = ['id', 'orderContext', 'price', 'createTime', 'phone', 'status'];

    queryOptions.group = ['id', 'orderContext', 'price', 'createTime', 'phone', 'status'];
    const orders = await Order.findAll(queryOptions);
    return {
        totalCount, orders
    };
}

async function deleteOrder(req) {
    const {id} = req.params;
    const deletedRows = await Order.destroy({
        where: {
            id: id
        }
    })
    if (deletedRows > 0) {
        console.log(`成功删除了 ${deletedRows} 条记录`);
    } else {
        throw new Error('未找到匹配的记录');
    }
}

async function batchOrder(items) {
    // 删除数据库中对应多个ID的菜品
    const deletedRows = await Order.destroy({
        where: {
            id: items // 使用数组形式传递所有要删除的菜品的 id
        }
    });

    if (deletedRows > 0) {
        console.log(`成功删除了 ${deletedRows} 条记录`);
        // 可选择返回一个删除成功的消息
        return {message: '批量删除成功'};
    } else {
        console.log('未找到匹配的记录');
        throw new Error('未找到匹配的记录');
        return {message: '批量删除失败'};
    }
}

module.exports = {
    findPage, deleteOrder, batchOrder, saveOrder
};